package com.ishopping.service.manage.service.impl;

import com.ishopping.common.core.base.service.AbstractBaseService;
import com.ishopping.service.manage.mapper.PermissionMapper;
import com.ishopping.api.manage.entity.Permission;
import com.ishopping.api.manage.enums.ResourceEnum;
import com.ishopping.api.manage.service.IPermissionService;
import com.ishopping.common.core.utils.tree.TreeNodeUtils;
import com.ishopping.common.core.vo.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service("permissionService")
public class PermissionServiceImpl extends AbstractBaseService<Permission> implements IPermissionService {

	@Autowired
	private PermissionMapper permissionMapper;

	/**
	 * 获取用户id下的权限信息
	 * @param userId
	 * @param resourceType
	 * @return List<Permission>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Permission> findPermissionsByUserId(Long userId, String resourceType){
		List<Permission> permissions = permissionMapper.queryPermissionsByUserId(userId, resourceType);
		return permissions;
	}

	/**
	 * 获取用户id下的权限信息
	 * @param userId
	 * @return List<Permission>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Permission> findPermissionsByUserId(Long userId){
		List<Permission> permissions = findPermissionsByUserId(userId, null);
		return permissions;
	}

	/**
	 * 获取菜单下的操作资源
	 * @param menuId
	 * @return List<Permission>
	 */
	@Transactional(readOnly = true)
	public List<Permission> findOperationsByMenuId(Long menuId){
		if(menuId == null){
			return Collections.emptyList();
		}
		List<Permission> operations = permissionMapper.queryOperations(menuId, ResourceEnum.OPERATION.getValue());
		return operations;
	}

	/**
	 * 获取菜单信息
	 * @return List<Permission>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Permission> findMenus(){
		List<Permission> menus = permissionMapper.queryMenus(ResourceEnum.MENU.getValue());
		return menus;
	}

	/**
	 * 加载权限树
	 * @param roleId
	 * @return List<TreeNode>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<TreeNode> findTree(Long roleId) {
		List<TreeNode> treeNodeList = permissionMapper.queryTreeNodes(roleId);
		List<TreeNode> newTreeNodeList = TreeNodeUtils.getFatherNodes(treeNodeList);
		return newTreeNodeList;
	}
}
